<template>
  <cu-layout navbar="search" navbar-bg="transparent" :navbar-placeholder="false" title="商品详情">
    <view class="">
      <uv-swiper
        :list="info.imgs"
        indicator
        indicator-mode="line"
        circular
        height="750rpx"
      />
    </view>
    <view class="cu-card rounded-0">
      <view class="flex-a">
        <view class="sku-logo hair-s">
          <image class="sku-img" :src="sku.img || $.defImg" mode="" />
        </view>
        <view class="ml-10">
          <view class="text-red">
            <cu-price :font-size="20" :value="sku.retail_price" /> / {{ sku.unit_name || '件' }}
          </view>
          <view class="mt-4 text-13">已选：<text class="">{{ sku.sku_name }}</text></view>
        </view>
      </view>
      <view class="bg-white mt-15">
        <view class="text-16 font-600">{{ info.name }}</view>
        <view class="flex-ba mt-10">
          <view class=""><text class="text-tips">原价：</text>{{ parseFloat(sku.retail_price) }}</view>
          <view class=""><text class="text-tips">库存：</text><text :class="{'text-error': !sku.stock}">{{ sku.stock }}</text></view>
          <view class=""><text class="text-tips">销量：</text>{{ info.sale_num || '999+' }}</view>
        </view>
      </view>
    </view>

    <view class="cu-card rounded-0">
      <view class="">
        <view class="mb-10">
          <text class="text-15 font-600">规格</text>
        </view>
        <view class="flex-w">
          <view
            v-for="item in info.sku"
            :key="item.sku_id"
            class="sku-item"
            :class="item.sku_id === sku.sku_id ? 'active' : ''"
            @click="state.skuId = item.sku_id"
          >
            {{ item.sku_name }}
          </view>
        </view>
      </view>
      <view class="mb-35 mt-25 flex-ba">
        <view class="flex-a">
          <view class="text-15 font-600 mr-10">数量</view>
          <view v-if="sku.stock > 0" class="text-tips text-13">有货</view>
          <view v-else class="text-error text-13">无货</view>
        </view>
        <view>
          <uv-number-box
            :decimal-length="2"
            input-format-disabled
            :min="0"
            :max="sku.stock"
            :input-width="50"
            :button-size="28"
            :model-value="cart.num"
            async-change
            @change="({value})=> onNumChange(value, i)"
          />
        </view>
      </view>
      <view>
        <uv-textarea v-model="state.remark" style="background-color: #fafafa;" placeholder="备注" maxlength="500" count />
      </view>
    </view>

    <view class="cu-card rounded-0">
      <view class="text-15 font-600 mb-12">商品分类</view>
      {{ info.cate_names }}
    </view>

    <view class="cu-footer">
      <view class="cu-footer-fixed flex-a px-20 hair-t shadow-t">
        <view class="flex-1 flex-ba text-center text-content ">
          <view class="" @click="$.router.go('/pages/index/index')">
            <view class="iconfont icon-shouye text-18 leading-20" />
            <view class="text-10 mt-2">首页</view>
          </view>
          <view class="" :class="info.collect_id ? 'text-primary' : ''" @click="onCollect">
            <view class="iconfont icon-biaoxing text-18 leading-20" />
            <view class="text-10 mt-2">收藏</view>
          </view>
          <view class="relative" @click="$.router.go('/pages/cart/index')">
            <view class="iconfont icon-gouwuche text-18 leading-20" />
            <view class="text-10 mt-2">购物车</view>
            <view class="absolute" style="top: -4px; right: -4px;"><uv-badge max="99" :value="cart.num" /></view>
          </view>
        </view>
        <view class="ml-40">
          <uv-button :disabled="!cart.num" shape="circle" color="linear-gradient(to right, #3c9cff, #398ade)" @click="buy">
            <view class="px-30">立即购买</view>
          </uv-button>
        </view>
      </view>
    </view>
  </cu-layout>
</template>

<script setup>
import {
  ref,
  reactive,
  computed,
  watch
} from 'vue'
import {
  onLoad
} from '@dcloudio/uni-app'
import $ from '@/sheep'
const state = reactive({
  skuId: 0,
  loading: false,
  remark: ''
})
const info = ref({})

const cart = computed(() => $.store('shop').cartList.find(v => v.sku_id === state.skuId) ?? {})
const sku = computed(() => info.value?.sku?.find(v => v.sku_id === state.skuId) ?? {})

watch(() => sku.value, (newVal) => {
  if (newVal.remark && !state.remark) {
    state.remark = newVal.remark
  }
})

onLoad(async(options) => {
  await $.store('shop').cartLoad()
  $.get('/Store/productDetail', {
    id: options.id
  }, {
    isShop: true
  }).then(res => {
    if (!res.success) {
      $.utils.showModal({
        title: '提示',
        content: res.msg,
        showCancel: false
      }).then(() => $.router.back())
      return false
    }
    info.value = res.data
    if (options.skuId && res.data.sku.find(v => v.sku_id === Number(options.skuId))) {
      state.skuId = Number(options.skuId)
    } else {
      state.skuId = res.data.sku[0].sku_id
    }
  })
})

function onNumChange(num) {
  $.debounce(() => {
    if (num <= 0) {
      num = 0
    }
    $.post('/Store/addCart', {
      sku_id: state.skuId,
      num
    }, {
      isShop: 1
    }).then(res => {
      if (res.success) {
        $.store('shop').cartLoad()
      } else {
        $.utils.toast(res.msg)
      }
    })
  }, 100)
}

async function onCollect() {
  if (state.loading) return
  state.loading = true

  let url = info.value.collect_id > 0 ? '/User/cancelProductCollect' : '/User/addProductCollect'
  let params = info.value.collect_id > 0 ? { id: info.value.collect_id } : { product_id: info.value.id }

  const res = await $.post(url, params, { isShop: 1 })
  $.utils.toast(res.msg)
  if (res.success) {
    info.value.collect_id = info.value.collect_id > 0 ? 0 : res.data.collect_id
  }
  state.loading = false
}

async function buy() {
  if (state.loading) return
  state.loading = true
  const res = await $.post('/Store/preSubmitOrder', { ids: [cart.value.id] }, { isShop: 1 })
  if (res.success) {
    $.router.go('/pages/order/confirm', { ids: cart.value.id })
  } else {
    $.utils.showModal({
      showCancel: false,
      content: res.msg
    }).then(() => {})
  }
}
</script>

<style lang="scss">
	.sku-logo {
		width: 100rpx;
		height: 100rpx;
		border-radius: 8prx;
		overflow: hidden;

		&::after {
			border-radius: 16rpx;
		}
	}

	.sku-img {
		display: block;
		width: 100%;
		height: 100%;
	}

	.sku-item {
		padding: 12rpx 24rpx;
		background-color: #ededed;
		border-radius: 8rpx;
		margin-right: 24rpx;
		margin-bottom: 24rpx;

		&.active {
			color: $uv-primary;
			background-color: #ecf5ff;
		}
	}
</style>
